package com.example.musicdemo.internal.collection

import android.content.Context
import android.database.Cursor
import android.os.Bundle
import androidx.fragment.app.FragmentActivity
import androidx.loader.app.LoaderManager
import androidx.loader.content.Loader
import com.example.musicdemo.internal.loader.MusicLoader
import java.lang.ref.WeakReference

class MusicCollection : LoaderManager.LoaderCallbacks<Cursor> {

    private var mContext: WeakReference<Context>? = null
    private lateinit var mLoaderManager: LoaderManager
    private var mLoadFinished = false
    private var mCallback: MusicCallbacks? = null

    companion object {
        const val LOADER_ID = 1
    }


    /**
     * 初始化collection的函数
     */
    fun onCreate(activity: FragmentActivity, callbacks: MusicCallbacks) {
        mContext = WeakReference(activity)
        mLoaderManager = activity.supportLoaderManager
        mCallback = callbacks
    }

    fun onDestroy() {
        mLoaderManager?.destroyLoader(LOADER_ID)

        mCallback = null
    }


    override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor> {
        mLoadFinished = false
        return MusicLoader.newInstance(mContext?.get())
    }

    /**
     * 查询完调用的函数
     */
    override fun onLoadFinished(loader: Loader<Cursor>, data: Cursor?) {
        if (!mLoadFinished) {
            mLoadFinished = true
            mCallback?.onMusicLoad(data)
        }
    }

    /**
     * 重置加载器
     */
    override fun onLoaderReset(loader: Loader<Cursor>) {
        mCallback?.onMusicReset()

    }

    /**
     * 加载器开始启动
     */
    fun loadMusic() {
        mLoaderManager.initLoader(LOADER_ID, null, this)
    }


    /**
     * 暴露给碎片或者活动调用的函数
     */
    interface MusicCallbacks {
        fun onMusicLoad(cursor: Cursor?)
        fun onMusicReset()
    }

}